﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;

namespace AutoUpdater.Utils
{
    /// <summary>
    /// ConvertHelper 的摘要说明
    /// </summary>
    public class ConvertHelper
    {
        public static object ChangeType(object obj, Type conversionType)
        {
            return ChangeType(obj, conversionType, Thread.CurrentThread.CurrentCulture);
        }
        /// <summary>
        /// 转换数据类型
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="conversionType"></param>
        /// <param name="provider"></param>
        /// <returns></returns>
        public static object ChangeType(object obj, Type conversionType, IFormatProvider provider)
        {

            Type nullableType = Nullable.GetUnderlyingType(conversionType);
            if (nullableType != null)
            {
                if (obj == null)
                {
                    return null;
                }
                //if (nullableType == typeof(DateTime?) || nullableType == typeof(DateTime))
                //{
                //    obj = ConvertToDateTime(obj); //时间转换
                //}
                return Convert.ChangeType(obj, nullableType, provider);
            }

            if (typeof(System.Enum).IsAssignableFrom(conversionType))
            {
                return Enum.Parse(conversionType, obj.ToString());
            }

            return Convert.ChangeType(obj, conversionType, provider);
        }

        /// <summary>
        /// 字节数组转为指定类型
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static T ChangeBytesToType<T>(byte[] bytes)
        {
            using (var ms = new MemoryStream())
            {
                ms.Write(bytes, 0, bytes.Length);
                var bf = new BinaryFormatter();
                ms.Position = 0;
                var x = bf.Deserialize(ms);
                return (T)x;
            }
        }

        /// <summary>
        /// 指定类型转为字节数组
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static byte[] ChangeTypeToBytes<T>(T obj)
        {
            var bf = new BinaryFormatter();
            using (var ms = new MemoryStream())
            {
                bf.Serialize(ms, obj);
                return ms.ToArray();
            }
        }
    }
}
